package com.hmdp.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.entity.ShopComments;
import com.hmdp.service.IShopCommentsService;
import com.hmdp.service.IShopService;
import com.hmdp.utils.SystemConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@RestController
@RequestMapping("/shop")
public class ShopController {

    @Resource
    public IShopService shopService;

    @Autowired
    private IShopCommentsService shopCommentsService;

    @PostMapping("/comment") //如果使用POST，实现自动POJO封装，contentType:"application/json;charset=utf-8"
    public Result saveComment(HttpServletRequest req){
        ShopComments sc = new ShopComments();
        //设置店铺id
        sc.setShopId(Long.valueOf(req.getParameter("shop_id")));
        //评价内容
        sc.setContent(req.getParameter("content"));
        //口味评分
        Integer taste = Integer.valueOf(req.getParameter("taste"));
        //环境评分
        Integer environment = Integer.valueOf(req.getParameter("environment"));
        //服务评分
        Integer service = Integer.valueOf(req.getParameter("service"));
        //种类评分
        Integer types = Integer.valueOf(req.getParameter("types"));
        //综合评分
        Integer score = (taste + environment + service + types) / 4; //平均取整

        sc.setTaste(taste);
        sc.setEnvironment(environment);
        sc.setService(service);
        sc.setTypes(types);
        sc.setScore(score);
        // 获取图片集合
        List<MultipartFile> scfiles = ((MultipartHttpServletRequest) req).getFiles("scfiles");
        // 然后调用函数将图片保存至本地,返回图片本地路径字符串集合的拼接
        String images = uploadFiles(scfiles);
        sc.setImages(images);
        return shopCommentsService.saveShopComment(sc);
    }

    /**
     * 根据传入的 List<MultipartFile> scfiles 图片集合，将其保存在本地，然后为每一张图片新建一个新的文件名，进行字符串拼接、
     */
    private String uploadFiles(List<MultipartFile> scfiles){
        StringBuilder images = new StringBuilder("");
        for(MultipartFile image : scfiles){
            try {
                // 获取原始文件名称
                String originalFilename = image.getOriginalFilename();
                // 生成新文件名
                String fileName = createNewFileName(originalFilename);
                // 保存文件
                image.transferTo(new File(SystemConstants.IMAGE_UPLOAD_DIR, fileName));
                // 返回结果
                log.debug("文件上传成功，{}", fileName);
                if("".equals(images.toString())){
                    images.append(fileName);
                }else{
                    images.append("," + fileName);
                }
            } catch (IOException e) {
                throw new RuntimeException("文件上传失败", e);
            }
        }
        return images.toString();
    }

    /**
     * 根据原始文件名称来新建一个新的文件名
     * @param originalFilename
     * @return
     */
    private String createNewFileName(String originalFilename) {
        // 获取后缀
        String suffix = StrUtil.subAfter(originalFilename, ".", true);
        // 生成目录
        String name = UUID.randomUUID().toString();
        int hash = name.hashCode();
        int d1 = hash & 0xF;
        int d2 = (hash >> 4) & 0xF;
        // 判断目录是否存在
        File dir = new File(SystemConstants.IMAGE_UPLOAD_DIR, StrUtil.format("/blogs/{}/{}", d1, d2));
        if (!dir.exists()) {
            dir.mkdirs();
        }
        // 生成文件名
        return StrUtil.format("/blogs/{}/{}/{}.{}", d1, d2, name, suffix);
    }

    /**
     * 根据id查询商铺信息
     * @param id 商铺id
     * @return 商铺详情数据
     */
    @GetMapping("/{id}")
    public Result queryShopById(@PathVariable("id") Long id) {
        return shopService.queryById(id);
    }

    /**
     * 新增商铺信息
     * @param shop 商铺数据
     * @return 商铺id
     */
    @PostMapping
    public Result saveShop(@RequestBody Shop shop) {
        // 写入数据库
        shopService.save(shop);
        // 返回店铺id
        return Result.ok(shop.getId());
    }

    /**
     * 更新商铺信息
     * @param shop 商铺数据
     * @return 无
     */
    @PutMapping
    public Result updateShop(@RequestBody Shop shop) {
        // 写入数据库
//        shopService.updateById(shop);
//        return Result.ok();
        return shopService.update(shop);
    }

    /**
     * 根据商铺类型滚动分页查询商铺信息
     * @param typeId 商铺类型
     * @param current 页码
     * @return 商铺列表
     */
    @GetMapping("/of/type")
    public Result queryShopByType(
            @RequestParam("typeId") Integer typeId,
            @RequestParam(value = "current", defaultValue = "1") Integer current,
            @RequestParam(value = "x", required = false) Double x,
            @RequestParam(value = "y", required = false) Double y
    ) {

        return shopService.queryShopByType(typeId,current,x,y);
    }

    /**
     * 根据商铺名称关键字分页查询商铺信息
     * @param name 商铺名称关键字
     * @param current 页码
     * @return 商铺列表
     */
    @GetMapping("/of/name")
    public Result queryShopByName(
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "current", defaultValue = "1") Integer current
    ) {
        // 根据类型分页查询
        Page<Shop> page = shopService.query()
                .like(StrUtil.isNotBlank(name), "name", name)
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 返回数据
        return Result.ok(page.getRecords());
    }
}
